//
//  ZYLoginMainVC.m
//  YiLin
//
//  Created by Zyark on 2018/5/29.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYLoginMainVC.h"
#import "ZYLoginView.h"
#import "ZYRegisterView.h"
#import "ZYForgetPasswordVC.h"
#import "ZYRegisterViewModel.h"
#import "ZYLoginViewModel.h"
#import "ZYIndexMainVC.h"
#import "ZYTabBarController.h"
#import "JKCountDownButton.h"
#import "AppDelegate.h"
#import "WLCaptcheButton.h"
#import "WeChatHelper.h"
#import "KxMenu.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

#define LOGIN_VIEW_HEIGHT ZYSCREEN_W * 1.16
#define REGISTER_VIEW_HEIGHT ZYSCREEN_W * 1.33

@interface ZYLoginMainVC ()<ZYLoginViewDelegate,ZYRegisterViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIImageView *loginArrowImageView;
@property (weak, nonatomic) IBOutlet UIImageView *registerArrowImageView;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (nonatomic,strong) ZYLoginView *loginView;
@property (nonatomic,strong) ZYRegisterView *registerView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgViewHeight;
@property (strong, nonatomic) UIView *bgColorView;
/**
 右侧菜单组
 */
@property(nonatomic,strong) NSArray *rightMenuItemArray;

@property(nonatomic,assign) BOOL isShowRightMenu;

/**右侧按钮*/
@property(nonatomic,strong) UIButton *rightBtn;

/**
 注册
 */
@property (nonatomic,strong) ZYRegisterViewModel *registerViewModel;

/**
 登录
 */
@property(nonatomic,strong) ZYLoginViewModel *loginViewModel;
@end

@implementation ZYLoginMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    [self setupTap];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.tabBarController.tabBar.hidden = YES;
    self.fd_interactivePopDisabled = YES;
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    self.tabBarController.tabBar.hidden = NO;
    self.fd_interactivePopDisabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//初始化右侧导航栏
-(void)setupRightButton{
    UIButton *button = [[UIButton alloc] init];
    button.frame = CGRectMake(0, 0, 80, 25);
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [button addTarget:self action:@selector(showRightMenu:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.borderColor = [UIColor whiteColor].CGColor;
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 3;
    button.layer.masksToBounds = YES;
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    if([[language userLanguage] hasPrefix:@"en"]){
        [button setTitle:[language getStringByKey:LC_ENGLISH] forState:UIControlStateNormal];
    }else{
        [button setTitle:[language getStringByKey:LC_CHINESE] forState:UIControlStateNormal];
    }
    [self.view addSubview:button];
    button.right = ZYSCREEN_W - 15;
    button.centerY = _loginBtn.centerY;
    _rightBtn = button;
}


-(void)setupRightMenuItem{
    ZYChangeLanguage *language = [[ZYChangeLanguage alloc] init];
    _rightMenuItemArray =
    @[
      [KxMenuItem menuItem:[language getStringByKey:LC_ENGLISH]
                     image:nil
                    target:self
                    action:@selector(changeLanguageByEnglish)],
      [KxMenuItem menuItem:[language getStringByKey:LC_CHINESE]
                     image:nil
                    target:self
                    action:@selector(changeLanguageByChinese)]];
}

/**
 显示右边菜单
 @param button 按钮
 */
-(void)showRightMenu:(UIButton *)button{
    _isShowRightMenu = !_isShowRightMenu;
    if(_isShowRightMenu){
        [KxMenu setTintColor:[UIColor whiteColor]];
        [KxMenu setTitleFont:[UIFont systemFontOfSize:14]];
//        [KxMenu showMenuInView:self.view fromRect:[self.view convertRect:button.frame fromView:button.superview] menuItems:_rightMenuItemArray withOptions:[self setupMenuConfig]];
        [KxMenu showMenuInView:self.view fromRect:button.frame  menuItems:_rightMenuItemArray  withOptions:[self setupMenuConfig]];
    }else{
        [KxMenu dismissMenu];
    }
}

/**
 切换英文
 */
-(void)changeLanguageByEnglish{
    _isShowRightMenu = !_isShowRightMenu;
    [super setLanguage:@"en"];
}
/**
 切换中文
 */
-(void)changeLanguageByChinese{
    _isShowRightMenu = !_isShowRightMenu;
    [super setLanguage:@"zh-Hans"];
}

-(void)changeLanguage{
    [super changeLanguage];
    //修改界面文字
    [self setupRightMenuItem];
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    if([[language userLanguage] hasPrefix:@"en"]){
        [_rightBtn setTitle:[language getStringByKey:LC_ENGLISH] forState:UIControlStateNormal];
    }else{
        [_rightBtn setTitle:[language getStringByKey:LC_CHINESE] forState:UIControlStateNormal];
    }
    [_loginBtn setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_LOGIN_LOGIN_BTN_TITLE] forState:UIControlStateNormal];
    [_loginBtn setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_LOGIN_LOGIN_BTN_TITLE] forState:UIControlStateSelected];
    [_registerBtn setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_LOGIN_REGISTER_BTN_TITLE] forState:UIControlStateNormal];
    [_registerBtn setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_LOGIN_REGISTER_BTN_TITLE] forState:UIControlStateSelected];
    [_loginView setupTitle];
    [_registerView setupTitle];
}

-(void)setupView{
//    _bgColorView.backgroundColor = [UIColor clearColor];
//    _bgView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor clearColor];
    _bgColorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H)];
    [self.view addSubview:_bgColorView];
    [self.view sendSubviewToBack:_bgColorView];
    [_bgColorView.layer addSublayer:[ZYUtils setGradualChangingColor:_bgColorView fromHexColorStr:kMainColorStartColorHexString toHexColorStr:kMainColorEndColorHexString locations:@[@0.3, @1.0]]];
//    [self.view.layer addSublayer:[ZYUtils setGradualChangingColor:self.view fromHexColorStr:kMainColorStartColorHexString toHexColorStr:kMainColorEndColorHexString locations:@[@0.3, @1.0]]];
    _loginView = [[ZYLoginView alloc] initWithFrame:_bgView.frame];
    _loginView.delegate = self;
    _loginView.height = LOGIN_VIEW_HEIGHT;
    _loginView.hidden = NO;
    [_bgView addSubview:_loginView];
    
    ZYWeakSelf(weakSelf)
    [_loginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.bgView).offset(30);
        make.bottom.equalTo(weakSelf.bgView);
        make.trailing.equalTo(weakSelf.bgView);
        make.leading.equalTo(weakSelf.bgView);
    }];
    
    _registerView = [[ZYRegisterView alloc] initWithFrame:_bgView.frame];
    _registerView.delegate = self;
    _registerView.height = REGISTER_VIEW_HEIGHT;
    _registerView.hidden = YES;
    [_bgView addSubview:_registerView];
    [_registerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.bgView).offset(30);
        make.bottom.equalTo(weakSelf.bgView);
        make.trailing.equalTo(weakSelf.bgView);
        make.leading.equalTo(weakSelf.bgView);
    }];
    [_loginBtn.titleLabel setFont:[UIFont systemFontOfSize:20]];
    [_registerBtn.titleLabel setFont:[UIFont systemFontOfSize:20]];
    [_loginBtn addTarget:self action:@selector(doLogin:) forControlEvents:UIControlEventTouchUpInside];
    [_registerBtn addTarget:self action:@selector(doRegister:) forControlEvents:UIControlEventTouchUpInside];
    [self doLogin:_loginBtn];
    
    [self setupButton:_registerBtn :LC_LOGIN_REGISTER_BTN_TITLE];
    [self setupButton:_loginBtn :LC_LOGIN_LOGIN_BTN_TITLE];
    _bgView.layer.cornerRadius = 8;
    _bgView.layer.masksToBounds = YES;
    
    
    [self setupRightMenuItem];
    [self setupRightButton];//初始化右侧切换语言
    
}

-(void)setupButton:(UIButton *)button :(NSString *)key{
    [button setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:key] forState:UIControlStateNormal];
    [button setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:key] forState:UIControlStateSelected];
    [button setTintColor:RGBA(255, 255, 255, 0)];
    [button setBackgroundColor:RGBA(255, 255, 255, 0)];
    [button setTitleColor:RGBA(255, 255, 255, 0.5) forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
}

#pragma mark - Event
-(void)doLogin:(id)button{
    if([button isSelected]){
        return;
    }
    [button setSelected:![button isSelected]];
    if([button isSelected]){
        [_registerBtn setSelected:NO];
        _loginView.hidden = NO;
        _registerView.hidden = YES;
        _bgViewHeight.constant = LOGIN_VIEW_HEIGHT;
        _loginArrowImageView.hidden = NO;
        _registerArrowImageView.hidden = YES;
    }
}

-(void)doRegister:(id)button{
    if([button isSelected]){
        return;
    }
    [button setSelected:![button isSelected]];
    if([button isSelected]){
        [_loginBtn setSelected:NO];
        _loginView.hidden = YES;
        _registerView.hidden = NO;
        _bgViewHeight.constant = REGISTER_VIEW_HEIGHT;
        _loginArrowImageView.hidden = YES;
        _registerArrowImageView.hidden = NO;
    }
}


#pragma mark - Getter
-(ZYRegisterViewModel *)registerViewModel{
    if(!_registerViewModel){
        _registerViewModel = [[ZYRegisterViewModel alloc] init];
    }
    return _registerViewModel;
}

-(ZYLoginViewModel *)loginViewModel{
    if(!_loginViewModel){
        _loginViewModel = [[ZYLoginViewModel alloc] init];
    }
    return _loginViewModel;
}

#pragma mark - LoginView delegate
//账号登录
-(void)loginView:(ZYLoginView *)loginView doLogin:(id)button{
    self.loginViewModel.username = [loginView getUsername];
    self.loginViewModel.password = [loginView getPassword];
    //监听状态
    [[self.loginViewModel.loginCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        ((UIButton *)button).enabled = !executing;
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
    @weakify(self);
    [[self.loginViewModel.loginCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_LOGIN_SUCCESS]];
        [self goToIndex];
    } error:^(NSError *error) {
        [[ToastHelper sharedToastHelper] toastError:[NSErrorHelper handleErrorMessage:error]];
    }];
    
}

//微信登录
-(void)loginView:(ZYLoginView *)loginView doWeChatLogin:(id)button{
    WeChatHelper *helper = [WeChatHelper new];
    [helper weChatLoginWithController:self];
}

//忘记密码
-(void)loginView:(ZYLoginView *)loginView doForgetPassword:(id)button{
    ZYForgetPasswordVC *vc = [[ZYForgetPasswordVC alloc] init];
//    ZYNavigationController *nav = [[ZYNavigationController alloc] initWithRootViewController:vc];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - RegisterView delegate
//注册
-(void)registerView:(ZYRegisterView *)registerView doRegister:(id)button{
    [self dismissKeyboard];
    self.registerViewModel.phone = [registerView getUsername];
    self.registerViewModel.password = [registerView getPassword];
    self.registerViewModel.rePassword = [registerView getRePassword];
    self.registerViewModel.code = [registerView getCode];
    @weakify(self);
    [[self.registerViewModel.registerCommand execute:nil] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_REGISTER_SUCCESS]];
        [self goToIndex];
    } error:^(NSError *error) {
        [[ToastHelper sharedToastHelper] toastError:[NSErrorHelper handleErrorMessage:error]];
    }];
    //监听状态
    [[self.registerViewModel.registerCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        ((UIButton *)button).enabled = !executing;
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
}

//获取验证码
-(void)registerView:(ZYRegisterView *)registerView doGetCode:(id)button{
    [self dismissKeyboard];
    JKCountDownButton *codeBtn =(JKCountDownButton *) button;
    NSString *phone = [registerView getUsername];
    self.registerViewModel.phone = phone;
    if(NULLString(phone)){
        [[ToastHelper sharedToastHelper] toast:[[ZYChangeLanguage sharedZYChangeLanguage]  getStringByKey:LC_ERROR_PHONE_OR_EMAIL_EMPTY]];
        return;
    }
    if(![ZYBasicHelper validateMobile:phone] && ![ZYBasicHelper validateEmail:phone]){
        [[ToastHelper sharedToastHelper] toast:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ERROR_PHONE_OR_EMAIL]];
        return;
    }
    if([ZYBasicHelper validateMobile:phone]){
        self.registerViewModel.modifyType = ZYModifyTypePhone;
    }else{
        self.registerViewModel.modifyType = ZYModifyTypeEmail;
    }
    [[self.registerViewModel.codeCommand execute:nil] subscribeNext:^(id x) {
        codeBtn.enabled = NO;
        //button type要 设置成custom 否则会闪动
        [codeBtn startCountDownWithSecond:60];
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_GET_CODE_SUCCESS]];
    } error:^(NSError *error) {
        [[ToastHelper sharedToastHelper] toastError:[NSErrorHelper handleErrorMessage:error]];
    }];
    //监听状态
    [[self.registerViewModel.codeCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        codeBtn.enabled = !executing;
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
}


/**
 跳转到首页
 */
-(void)goToIndex{
    [[ZYTabBarController sharedInstance] setUp];
    [ZYTabBarController sharedInstance].selectedIndex = 0;
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    app.window.rootViewController = [ZYTabBarController sharedInstance];
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 配置菜单参数
 
 @return OptionalConfiguration
 */
-(OptionalConfiguration)setupMenuConfig{
    Color textColor;
    textColor.R = 102/255.0;
    textColor.G = 102/255.0;
    textColor.B = 102/255.0;
    Color menuBackgroundColor;
    menuBackgroundColor.R = 1;
    menuBackgroundColor.G = 1;
    menuBackgroundColor.B = 1;
    OptionalConfiguration config;
    config.arrowSize = 0;//指示箭头大小
    config.marginXSpacing = 5;  //MenuItem左右边距
    config.marginYSpacing = 8;  //MenuItem上下边距
    config.intervalSpacing = 10;//MenuItemImage与MenuItemTitle的间距
    config.menuCornerRadius = 5;//菜单圆角半径
    config.maskToBackground = NO;//是否添加覆盖在原View上的半透明遮罩
    config.hasSeperatorLine = NO;
    config.textColor = textColor; //menuItem字体颜色
    config.menuBackgroundColor = menuBackgroundColor;
    config.hasSeperatorLine = NO;
    return config;
}
@end
